<?php
namespace app\common\service;

use app\common\model\Cart as CartModel;
use think\Loader;

class Cart{


    public function allByUser($id){

        $carts = CartModel::where("user_id",$id)->select();
        return $carts;
    }

    /**
     * 给指定的用户指定的产品添加一个
     * @param $product_id
     * @param $user_id
     * @return array|mixed
     */
    public function addOne($product_id,$user_id){
        $cart = CartModel::where('product_id',$product_id)->where('user_id',$user_id)->find();
        if($cart){
            $cart->num = intval($cart->num)+1;
            $cart->save();
            return $cart->id;
        }else{
            $data = [];
            $data['product_id'] = $product_id;
            $data['user_id'] = $user_id;
            $data['num'] = 1;
            $result = $this->insert($data);
            return $result;
        }
    }

    /**
     * 给指定用户的指定产品减去一个
     * @param $product_id
     * @param $user_id
     * @return mixed
     */
    public function subOne($product_id,$user_id){
        $cart = CartModel::where(['product_id'=>$product_id,'user_id'=>$user_id])->find();
        if($cart){
            $cart->num = intval($cart->num)-1;
            if($cart->num <= 0) $cart -> num = 0;
            $cart->save();
            return $cart->id;
        }
        return false;
    }

    public function insert($data){

        $cartModel = new CartModel();

        $validate = Loader::validate("CartValidate");
        $checkResult = $validate ->scene("add") -> check($data);
        if(!$checkResult){
            return ['state'=>0,'message'=>$validate->getError()];
        }

        $result = $cartModel->allowField(['user_id','product_id','num'])->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$cartModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$cartModel->id];

    }



    public function update($data){
        $cartModel = new CartModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $validate = Loader::validate("CartValidate");
        $checkResult = $validate ->scene('edit') -> check($data);
        if(!$checkResult){
            return ['state'=>0,'message'=>$validate->getError()];
        }

        $result = $cartModel->allowField(['id','user_id','product_id','num'])->save($data,['id'=>intval($data['id'])]);


        if(false === $result){
            return ['state'=>0,'message'=>$cartModel->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function delete($ids){
        $cartModel = new CartModel();

        $count = $cartModel ->destroy($ids);

        return $count;
    }
}
